<template>
    <div id="Content-page">
        <Paging :pagData="[{ name: '首页推荐', router: '' }]" />
        <div class="content-main">
            <div class="global-display subbuttom"><el-button type="primary" @click="drawer = true">新增推荐</el-button></div>
            <el-table :data="tableData" style="width: 100%">
                <el-table-column label="封面图">
                    <template #default="scope">
                        <el-image style="width: 40px; height: 40px; border-radius: 5px;" :src="scope.row.cover" fit="cover"
                            :preview-src-list="[scope.row.cover]" preview-teleported />
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="关联商品" />
                <el-table-column prop="price" label="价格" />
                <el-table-column prop="visitTimes" label="访问次数" />
                <el-table-column width="250" prop="recommendDate" label="推荐日期">
                    <template #default="scope">
                        {{ formatDate(scope.row.recommendDate[0]) + " 至 " + formatDate(scope.row.recommendDate[1]) }}
                    </template>
                </el-table-column>
                <el-table-column prop="saleIncr" label="销量增长" />
                <el-table-column prop="dayAvgIncr" label="日均增长" />
                <el-table-column prop="sort" label="排序" />
                <el-table-column label="操作" fixed="right">
                    <template #default="scope">
                        <el-button type="primary" @click="editGoods(scope.row)">编辑</el-button>
                        <el-button type="danger" @click="deleteGoods(scope.row._id, scope.$index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>
    <el-drawer v-model="drawer" title="I am the title" style="min-width:500px;">
        <div>
            <div>
                <h4>封面图</h4>
                <UploadImg width="200px" :uploadImgurl="goodsData.cover" />
            </div>
            <div>
                <h4>推荐时间</h4>
                <el-date-picker v-model="goodsData.recommendDate" type="daterange" range-separator="至"
                    start-placeholder="开始时间" end-placeholder="结束时间" />
            </div>
            <div>
                <h4>排序</h4>
                <el-input-number v-model="goodsData.sort" :min="0" />
            </div>
            <div v-if="tableSelect.length > 0">
                <h4>已选择商品</h4>
                <el-table :data="tableSelect" style="width: 100%">
                    <el-table-column prop="name" label="商品" />
                    <el-table-column prop="price" label="售价" />
                    <el-table-column prop="saleNum" label="销量" />
                    <el-table-column prop="category" label="所属分类" />
                </el-table>
            </div>
            <h4>选择关联商品</h4>
            <el-table :data="goodsList" highlight-current-row @current-change="handleCurrentChange">
                <el-table-column prop="name" label="商品" />
                <el-table-column prop="price" label="售价" />
                <el-table-column prop="saleNum" label="销量" />
                <el-table-column prop="category" width="120" label="所属分类" />
            </el-table>
        </div>
        <el-pagination class="pager-next" background layout="prev, pager, next" :total="total" hide-on-single-page
            @current-change="currentChange" @size-change="sizeChange" />
        <!-- 提交 -->
        <div class="right-upload-button">
            <el-button type="primary" class="submit-button" :loading="loadingBtn" @click="submitData">提交</el-button>
        </div>
    </el-drawer>
</template>

<script setup>
import UploadImg from "@/page/component/upload.vue";
// 顶部导航组件
import Paging from '@/page/component/Paging-component.vue';
import { formatDate } from "@/utils";
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
const $router = useRouter();  // 这是路由跳转的
import request from '@/api/request.js';
const goodsData = ref({})
// 选中商品
const tableSelect = ref([]);
// 所有商品
const goodsList = ref([]);
const page = ref(1);
const size = ref(20);
const total = ref(0);

// 轮播图
const tableData = ref([]);
const drawer = ref(false)
onMounted(async () => {
    const res = await request.get('/getRecommendGoods');
    requestApi();
    console.log(res);
    tableData.value = res.data;
});
const editGoods = (row) => {
    console.log(row);
    drawer.value = true;
    goodsData.value = JSON.parse(JSON.stringify(row));
    tableSelect.value = [goodsList.value.find(item => item._id == row.goodsId)]
    // $router.push('/NewRecommendation?_id=' + _id);
}
// 删除商品
import { ElMessage, ElMessageBox } from 'element-plus';
function deleteGoods(id, index) {
    ElMessageBox.confirm('确定删除该商品吗?', '删除提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true,
        }
    )
        .then(async () => {
            await request.delete('/delRecommendGoods/' + id);
            tableData.value.splice(index, 1);
        });
}

async function requestApi() {
    const res = await request.get("/getGoodsList", {
        page: page.value,
        size: size.value,
    });
    console.log(res);
    goodsList.value = res.data.list;
    total.value = res.data.total;
}
// 分页
async function currentChange(event) {
    page.value = event;
    requestApi();
}
// 分页
async function sizeChange(event) {
    size.value = event;
    requestApi();
}
// 子组件上传图片成功触发
import emitter from "@/api/event.js";
emitter.on("upload-image-Success", (res) => {
    console.log(res);
    goodsData.value.cover = res.url;
});

// 选择商品
function handleCurrentChange(val) {
    tableSelect.value = [val];
    goodsData.value.categoryId = val.categoryId;
    goodsData.value.goodsId = val._id;
}
// 提交
const loadingBtn = ref(false);
async function submitData() {
    loadingBtn.value = true;
    try {
        const {_id,saleIncr, visitTimes,...assets} = goodsData.value;
        // 编辑
        if (_id) {
            await request.post("/editRecommendGoods", assets);
        } else {
            await request.post("/addRecommendGoods", assets);
        }
        loadingBtn.value = false;
        const res = await request.get('/getRecommendGoods');
        drawer.value = false;
        tableData.value = res.data;
    } catch (error) {
        console.log(error);
        loadingBtn.value = false;
    }
}
</script>

<style>
.reco-type {
    font-size: 18px;
    font-weight: bold;
}
</style>